﻿
#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QDateTime>
#include <QDebug>
#include <QDesktopServices>
#include <QDir>
#include <QJsonDocument>
#include <QJsonObject>
#include <QThread>
#include <QUrl>
#include <filedirutils.h>
#include <QStandardItemModel>
#include <QStandardItem>
#include <QFileSystemModel>

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent)
  , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    /********** 待处理部分 ************/
    {
        ui->groupBox_5->hide();
    }

    auto _DesktopLocation        = QStandardPaths::standardLocations(QStandardPaths::DesktopLocation).first();
    auto _DocumentsLocation      = QStandardPaths::standardLocations(QStandardPaths::DocumentsLocation).first();
    auto _FontsLocation          = QStandardPaths::standardLocations(QStandardPaths::FontsLocation).first();
    auto _ApplicationsLocation   = QStandardPaths::standardLocations(QStandardPaths::ApplicationsLocation).first();
    auto _MusicLocation          = QStandardPaths::standardLocations(QStandardPaths::MusicLocation).first();
    auto _MoviesLocation         = QStandardPaths::standardLocations(QStandardPaths::MoviesLocation).first();
    auto _PicturesLocation       = QStandardPaths::standardLocations(QStandardPaths::PicturesLocation).first();
    auto _TempLocation           = QStandardPaths::standardLocations(QStandardPaths::TempLocation).first();
    auto _HomeLocation           = QStandardPaths::standardLocations(QStandardPaths::HomeLocation).first();
    auto _DataLocation           = QStandardPaths::standardLocations(QStandardPaths::DataLocation).first();
    auto _CacheLocation          = QStandardPaths::standardLocations(QStandardPaths::CacheLocation).first();
    auto _GenericDataLocation    = QStandardPaths::standardLocations(QStandardPaths::GenericDataLocation).first();
    auto _RuntimeLocation        = QStandardPaths::standardLocations(QStandardPaths::RuntimeLocation).first();
    auto _ConfigLocation         = QStandardPaths::standardLocations(QStandardPaths::ConfigLocation).first();
    auto _DownloadLocation       = QStandardPaths::standardLocations(QStandardPaths::DownloadLocation).first();
    auto _GenericCacheLocation   = QStandardPaths::standardLocations(QStandardPaths::GenericCacheLocation).first();
    auto _GenericConfigLocation  = QStandardPaths::standardLocations(QStandardPaths::GenericConfigLocation).first();
    auto _AppDataLocation        = QStandardPaths::standardLocations(QStandardPaths::AppDataLocation).first();
    auto _AppConfigLocation      = QStandardPaths::standardLocations(QStandardPaths::AppConfigLocation).first();
    auto _AppLocalDataLocation   = QStandardPaths::standardLocations(QStandardPaths::AppLocalDataLocation).first();

    QString configPath;
#ifdef Q_OS_WIN32
    auto roamingDir = QFileInfo(_AppDataLocation).absolutePath();
    configPath = roamingDir;
#else
    configPath = QStandardPaths::locate(QStandardPaths::ConfigLocation, QString(), QStandardPaths::LocateDirectory);
#endif
    QDir dir(configPath + "/Code/User/workspaceStorage/");

    QFileInfoList entryInfoList = dir.entryInfoList(QDir::Filter::NoDotAndDotDot | QDir::Filter::Dirs);
    int count = entryInfoList.length();
    ui->projectCount->setText(QString::number(count));

    qint64 space = 0;

    ui->projectTableWidget->setRowCount(count);
    ui->projectTableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); // 列表的头部理所当然需要拉伸嘛
    for (int i =0;i<count;i++) {
        QString fileName = entryInfoList[i].fileName();
        QString filePath = entryInfoList[i].absoluteFilePath();
        QTableWidgetItem *item = new QTableWidgetItem;
        item->setData(Qt::DisplayRole, fileName);
        item->setData(Qt::UserRole, filePath);
        ui->projectTableWidget->setItem(i,0,item);

        qint64 currentSpace = 0;
        currentSpace = recursiveFileInfoSize(entryInfoList[i]);
        space += currentSpace;

        QTableWidgetItem *itemSize = new QTableWidgetItem;
        itemSize->setTextAlignment(Qt::AlignHCenter);
        itemSize->setData(Qt::DisplayRole, currentSpace/1000/1000.0);
        itemSize->setData(Qt::UserRole, filePath);
        ui->projectTableWidget->setItem(i,1, itemSize);


        QTableWidgetItem *itemDate = new QTableWidgetItem;
        itemDate->setTextAlignment(Qt::AlignHCenter);
        QDateTime localCreated = QFileInfo(filePath).birthTime();
        itemDate->setData(Qt::DisplayRole, localCreated.toString(u8"yyyy.MM.dd hh:mm:ss"));
        itemDate->setData(Qt::UserRole, filePath);
        qDebug() << itemDate->data(Qt::DisplayRole).toString();
        ui->projectTableWidget->setItem(i,2, itemDate);
    }
    ui->projectSpaceUsage->setText(QString::number(space/1000.0/1000/1000, 'f', 2) + "G");
    ui->projectTableWidget->setSortingEnabled(true);
    ui->projectTableWidget->sortItems(2, Qt::SortOrder::DescendingOrder);
}
MainWindow::~MainWindow()
{

}

qint64 MainWindow::recursiveFileInfoSize(QFileInfo entry)
{
    QDir dir(entry.absoluteFilePath());
    QFileInfoList entryInfoList = dir.entryInfoList(QDir::Filter::NoDotAndDotDot | QDir::Filter::AllEntries | QDir::Filter::Hidden);
    qint64 space = 0;
    foreach(auto entry, entryInfoList) {
        if (entry.isDir()) {
            space += recursiveFileInfoSize(entry);
        } else if (entry.isFile()) {
            space += entry.size();
        }
    }
    return space;
}

qint64 MainWindow::recursiveFileInfoCount(QFileInfo entry)
{
    QDir dir(entry.absoluteFilePath());
    QFileInfoList entryInfoList = dir.entryInfoList(QDir::Filter::NoDotAndDotDot | QDir::Filter::AllEntries | QDir::Filter::Hidden);
    qint64 count = 0;
    foreach(auto entry, entryInfoList) {
        if (entry.isDir()) {
            count += recursiveFileInfoCount(entry);
        } else if (entry.isFile()) {
            count ++;
        }
    }
    return count;
}

void MainWindow::setStatus(const QString &text)
{
    ui->status->setText(text);
}

void MainWindow::on_projectTableWidget_itemChanged(QTableWidgetItem *item)
{
//    QString filePath = item->data(Qt::UserRole).toString();
//    qDebug() << "filePath:" << filePath;
//    QDir dir(filePath);
//    if (dir.exists()) {
//        QFileInfoList entryInfoList = dir.entryInfoList(QDir::Filter::NoDotAndDotDot | QDir::Filter::Files);
//        qint64 space = 0;
////        foreach(auto entry, entryInfoList) {
////            space += entry.size();
////        }

//        ui->currentProjectSpace->setText(QString::number(space));
//        QDateTime localCreated = QFileInfo(filePath).created();
//        ui->currentProjectCreated->setText(localCreated.toString(u8"yyyy.MM.dd hh:mm:ss"));
//    }
}

void MainWindow::on_projectTableWidget_itemSelectionChanged()
{
    QString filePath = ui->projectTableWidget->currentItem()->data(Qt::UserRole).toString();
    ui->lineEdit_path->setText(filePath);
//    qDebug() << "filePath:" << filePath;
    QDir dir(filePath);
    if (dir.exists()) {
        QFileInfoList entryInfoList = dir.entryInfoList(QDir::Filter::NoDotAndDotDot | QDir::Filter::Files);
        qint64 space = 0;
        space = recursiveFileInfoSize(filePath);
        ui->currentProjectSpace->setText(QString::number(space/1000/1000.0, 'f', 2) + "M");
        QDateTime localCreated = QFileInfo(filePath).birthTime();
        ui->currentProjectCreated->setText(localCreated.toString(u8"yyyy.MM.dd hh:mm:ss"));
        QDateTime localAccess = QFileInfo(filePath).fileTime(QFile::FileModificationTime);
        ui->currentProjectAccess->setText(localAccess.toString(u8"yyyy.MM.dd hh:mm:ss"));
        setStatus(QString(u8"选中: %1, 占用: %2").arg(filePath).arg(QString::number(space/1000/1000.0, 'f', 2) + "M"));

        // 当目录存在则显示目录内容：目录、文件、隐藏的目录与文件，不包含 . 与 .. 目录
        QFileSystemModel *model = new QFileSystemModel;
        model->setFilter(QDir::Dirs|QDir::Files|QDir::Hidden|QDir::NoDotAndDotDot);
        model->setNameFilterDisables(false);
        model->setRootPath(filePath);

        ui->currentProjectTreeView->setModel(model);
        ui->currentProjectTreeView->setRootIndex(model->index(filePath));
        /* 列表的头部理所当然需要拉伸嘛 */
        ui->currentProjectTreeView->header()->setSectionResizeMode(QHeaderView::ResizeToContents); 

        QString workspace = QString(u8"%1/workspace.json").arg(filePath);
        bool worskspace_exists = QFileInfo::exists(workspace);
        ui->tab_workspace->setEnabled(worskspace_exists);
        if (worskspace_exists) {
            QFile file(workspace);
            file.open(QFile::ReadOnly);
            QByteArray content = file.readAll();
            ui->textBrowser->setPlainText(content);
            QJsonDocument document = QJsonDocument::fromJson(content);
            QJsonObject object = document.object();
            if (object.keys().contains(u8"folder")) {
                ui->currentProjectType->setText(u8"folder");
                QString folderPath = QUrl(object.value(u8"folder").toString()).toLocalFile();
                ui->lineEdit_name->setText(folderPath);
                ui->folderPath->setText(folderPath);
                ui->folderPath->setToolTip(folderPath);
                QFileInfo folder(folderPath);
                if (folder.exists() && folder.isDir()) {
                    QThread *thread = new QThread;
                    FileDirUtils *fileutils = new FileDirUtils;
                    fileutils->moveToThread(thread);
                    connect(thread, &QThread::started, fileutils, &FileDirUtils::getAsyncFileInfoCount);
                    connect(fileutils, &FileDirUtils::finish, thread, &QThread::quit);
                    connect(fileutils, &FileDirUtils::getAsyncFileInfoCountSingal, this, [=](qint64 filesCount){
                        ui->folderFilesCount->setText(QString::number(filesCount, 'f', 0));
                    });
                    connect(thread, &QThread::finished, this, [=]() {
                        qint64 filesCount = fileutils->getCount();
                        ui->folderFilesCount->setText(QString::number(filesCount, 'f', 0));
                    });
                    fileutils->setDirPath(folder.absoluteFilePath());
                    thread->start();

//                    qint64 filesCount = recursiveFileInfoCount(folder);
//                    ui->folderFilesCount->setText(QString::number(filesCount, 'f', 0));
                    ui->currentProjectOverdue->setText(u8"否");
                } else {
                    ui->folderFilesCount->setText(u8"0");
                    ui->currentProjectOverdue->setText(u8"是");
                }
            }
        }
    }
}

void MainWindow::on_openCurrentDir_clicked()
{
    QTableWidgetItem *currentItem = ui->projectTableWidget->currentItem();
    if (currentItem == nullptr) return;
    QString filePath = currentItem->data(Qt::UserRole).toString();
    QDesktopServices::openUrl(QUrl::fromLocalFile(filePath));
}

void MainWindow::on_currentProjectTreeWidget_itemSelectionChanged()
{
    // QTreeWidgetItem *item = ui->currentProjectTreeWidget->currentItem();
}

void MainWindow::on_openFolderExists_clicked()
{
    QString folderPath = ui->folderPath->text();
    if (QFileInfo::exists(folderPath)) {
        QDesktopServices::openUrl(QUrl::fromLocalFile(folderPath));
        setStatus(QString(u8"打开文件夹: %1").arg(folderPath));
    } else {
        setStatus(QString(u8"文件夹不存在: %1").arg(folderPath));
    }
}


void MainWindow::on_pushButton_clean_up_projects_clicked() {
    qDebug() << "clean up projects";
}

void MainWindow::on_pushButton_clean_up_tmp_projects_clicked() {
    qDebug() << "clean up tmp projects";
}
